<template>
  <div class="container">
    <el-card shadow="hover">
      <div class="toolbar">
        <el-button type="primary" @click="load" :loading="loading" icon="Refresh">
          加载数据
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        highlight-current-row
        class="custom-table"
        empty-text="暂无台账记录"
      >
        <!-- 动态字段列 -->
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.fields[col.prop]?.value || '-' }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="onEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑记录" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item
          v-for="col in columns"
          :label="col.label"
          :key="col.prop"
        >
          <el-input v-model="(editForm.fields[col.prop].value)"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchLedgerRecords, updateLedgerRecord, deleteLedgerRecord ,fetchSingleLedgerRecord} from '@/api/ledger'
import type { ColumnMeta, LedgerRecord } from '@/types/ledger'

const columns = ref<ColumnMeta[]>([])
const tableData = ref<LedgerRecord[]>([])
const loading = ref(false)

const editDialogVisible = ref(false)
const editForm = ref<LedgerRecord | null>(null)

const load = async () => {
  loading.value = true
  try {
    const res = await fetchLedgerRecords()
    columns.value = res.columns
    tableData.value = res.rows
  } catch (e) {
    console.error('加载失败', e)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}
const onEdit = async (row: LedgerRecord) => {
  try {
    loading.value = true
    const res = await fetchSingleLedgerRecord(row.recordId)
    console.log("res")
    console.log(res)
    const { rows, columns: cols } = res

    if (!rows || rows.length === 0) {
      ElMessage.warning('未找到该记录')
      return
    }
    columns.value = cols              
    editForm.value = rows[0]    
    editDialogVisible.value = true    
  } catch (e) {
    console.error('加载记录失败', e)
    ElMessage.error('加载记录失败')
  } finally {
    loading.value = false
  }
}


const submitEdit = async () => {
  if (!editForm.value) return
  const payload = {
    ledgerId: editForm.value.ledgerId,
    recordId: editForm.value.recordId,
    userId: editForm.value.userId,
    fields: editForm.value.fields
  }
  try {
    await updateLedgerRecord(payload)
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    load()
  } catch (err) {
    ElMessage.error('更新失败')
  }
}


const onDelete = async (row: LedgerRecord) => {
  try {
    await ElMessageBox.confirm('确认删除此记录？', '提示', {
      type: 'warning'
    })
    await deleteLedgerRecord(row.recordId)
    ElMessage.success('删除成功')
    load()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error('删除失败')
  }
}


// 页面初始化加载数据
load()
</script>

<style scoped>
.container {
  padding: 32px;
  background: #f5f7fa;
  min-height: 100vh;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
}

.custom-table {
  border-radius: 12px;
  overflow: hidden;
}

.el-table .cell {
  font-size: 14px;
  padding: 10px 8px;
}

.el-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}
</style>
